#!/usr/bin/env node

// console.log("hello");

const program = require("commander"); //命令工具
const inquirer = require("inquirer"); //用于和命令行交互的工具
const download = require("download-git-repo"); //用于从git上面下载模板
const chalk = require("chalk"); //命令行美化工具
const ora = require("ora"); //加载中的loading
const symbols = require("log-symbols");
const handlebars = require("handlebars");

const fs = require("fs");

program
  .version(require("../package").version, "-v,-version") //查看版本号的命令
  .command("init <name>") // init name(项目名称) 命令
  .action(name => {
    inquirer
      .prompt([
        {
          type: "input",
          name: "author",
          message: "请输入你的名字"
        },
        {
          type: "input",
          name: "description",
          message: "请输入项目描述"
        }
      ])
      .then(answer => {
        //提示正在拉取模板
        const process = ora("正在拉取模板...");
        process.start();
        //从gitee上面下载模板
        download(
          "https://gitee.com:ren_wei_1/react-templates",
          name,
          { clone: true },
          error => {
            // console.log(error);
            if (error) {
              //如果拉取失败的话
              process.fail();
              //打印出错误信息
              console.log(symbols.error, chalk.red(error));
            } else {
              //拉取成功的时候
              process.succeed();
              const fileName = `${name}/package.json`;
              const meta = {
                name,
                author: answer.author,
                description: answer.description
              };
              if (fs.existsSync(fileName)) {
                const content = fs.readFileSync(fileName).toString();
                const result = handlebars.compile(content)(meta);
                fs.writeFileSync(fileName, result);
              } else {
                console.log(symbols.error, chalk.red(`${fileName}不存在`));
              }
              console.log(symbols.success, chalk.green("创建成功"));
              console.log(symbols.info, chalk.green(`cd ${name}`));
              console.log(symbols.info, chalk.green(`yarn / npm install`));
              console.log(
                symbols.info,
                chalk.green(`yarn start / npm run start`)
              );
            }
          }
        );
      });
  });

program.parse(process.argv);
